<?php

namespace App\Http\Requests\Admin;
use App\Http\Models\Admin\Admin;
use App\Http\Requests\Common\BaseRequest as Request;

class AuthRequest extends Request
{
    //
    public function login(){
      //
      $data = [
        'title' => '管理员|登陆',
        'redirect_url' => route('admin.admin.center'),
      ];
      return view('admin.auth.login',compact('data'));
    }
    //
    public function check_login(){
      //检查是否登录
        if (session('admin')) {
            return self::_json([], 1, '已存在登录信息!');
        }
        //
        $rules = [
            "account"      => "required|min:2|max:20",
            "password"     => "required|min:2|max:80",
            "_token"       => "required|min:2|max:80",
            "redirect_url" => "required|url",
        ];
        $message = [
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "url"      => ":attributes不合法",
        ];
        $attributes = [
            "account"      => "用户账号",
            "password"     => "登录密码",
            "_token"       => "认证字段",
            "redirect_url" => "重定向地址",
        ];
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //
        $account = $data['account'];
        $passord = md5($data['password']);
        $model   = Admin::where(function ($query) use ($account) {
            $query->where('account', $account);
            $query->orWhere('mobile', $account);
            $query->orWhere('email', $account);
        });
        $admin = $model->where('status', 1)
            ->where('password', $passord)
            ->select('id', 'name', 'account')
            ->first();
        if (empty($admin)) {
                return self::_json([], 1, '账号或密码错误!');
        }
        //登录成功
        session(['admin' => $admin->toArray()]);
        return self::_json([], 0, '登录成功！', $data['redirect_url']);
     }
    //
    public function logout(){
       $admin = session('admin');
       session(['admin' => null]);
       return redirect()->route('admin.auth.login');
    }
}
